package com.example.dingding.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class MyCorsConfig {
    @Bean
    //配置跨域过滤器
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        System.out.println("跨域");
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedOriginPattern("*");//允许跨域的地址
        corsConfiguration.addAllowedMethod("*");//允许提交的方式
        corsConfiguration.addAllowedHeader("*");//允许头部携带参数
        corsConfiguration.addExposedHeader("token");//可以在头部添加变量
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);//过滤的规则
        FilterRegistrationBean<CorsFilter> corsFilterFilterRegistrationBean = new FilterRegistrationBean<>(new CorsFilter(corsConfigurationSource));
        //重点在此
        corsFilterFilterRegistrationBean.setOrder(1);//启动的顺序
        return corsFilterFilterRegistrationBean;
    }
}
